package com.uddenberg.wt.providers;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.uddenberg.wt.dbdefinitions.FoodOtherDataDefinition;
import com.uddenberg.wt.dbdefinitions.FoodOtherDataDefinition.FoodOtherDataColumns;

public class FoodOtherDataProvider extends ContentProvider {
	@SuppressWarnings("unused")
	private static final String TAG = "FoodOtherDataProvider";
	
	private static final String DATABASE_NAME = "foodother.db";
    private static final int DATABASE_VERSION = 1;
    
    private static HashMap<String, String> sFoodOtherDataProjectionMap;
    private static final UriMatcher sUriMatcher;
    
    private static final int FOOD_OTHER = 1;
    private static final int FOOD_OTHER_ID = 2;
    
    /**
     * This creates/opens the database.
     */
    private static class DatabaseOpenHelper extends SQLiteOpenHelper {
        DatabaseOpenHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
 
        @Override
        public void onCreate(SQLiteDatabase db) {
        	db.execSQL("CREATE TABLE food_other " +
                	"("+FoodOtherDataColumns._ID+" INTEGER primary key autoincrement, " + 
                	FoodOtherDataColumns.DATE+" INTEGER DEFAULT 0 NOT NULL," +
                	FoodOtherDataColumns.CAFFEINE+" INTEGER DEFAULT 0 NOT NULL," +
                	FoodOtherDataColumns.SNACK+" INTEGER DEFAULT 0 NOT NULL," +
                	FoodOtherDataColumns.HEALTHY+" INTEGER DEFAULT 0 NOT NULL);");
        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        	Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
        	db.execSQL("DROP TABLE IF EXISTS food_other;");
        	onCreate(db);
        }
    }
    
    private DatabaseOpenHelper mDatabaseOpenHelper;
    
    @Override
    public boolean onCreate() {
    	mDatabaseOpenHelper = new DatabaseOpenHelper(getContext());
        return true;
    }
    
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables("food_other");

        switch (sUriMatcher.match(uri)) {
        case FOOD_OTHER:
            qb.setProjectionMap(sFoodOtherDataProjectionMap);
            break;

        case FOOD_OTHER_ID:
            qb.setProjectionMap(sFoodOtherDataProjectionMap);
            qb.appendWhere(FoodOtherDataColumns._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = FoodOtherDataColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = mDatabaseOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }
    
    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case FOOD_OTHER:
            return FoodOtherDataColumns.CONTENT_TYPE;

        case FOOD_OTHER_ID:
            return FoodOtherDataColumns.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }
    
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        // Validate the requested uri
        if (sUriMatcher.match(uri) != FOOD_OTHER) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        // Make sure that the fields are all set
        if (values.containsKey(FoodOtherDataColumns.DATE) == false) {
            values.put(FoodOtherDataColumns.DATE, 0);
        }

        if (values.containsKey(FoodOtherDataColumns.CAFFEINE) == false) {
            values.put(FoodOtherDataColumns.CAFFEINE, 0);
        }
        
        if (values.containsKey(FoodOtherDataColumns.SNACK) == false) {
            values.put(FoodOtherDataColumns.SNACK, 0);
        }
        
        if (values.containsKey(FoodOtherDataColumns.HEALTHY) == false) {
            values.put(FoodOtherDataColumns.HEALTHY, 0);
        }
        

        SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase();
        long rowId = db.insert("food_other", FoodOtherDataColumns.DATE, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(FoodOtherDataColumns.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }
    
    
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case FOOD_OTHER:
            count = db.delete("food_other", where, whereArgs);
            break;

        case FOOD_OTHER_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.delete("food_other", FoodOtherDataColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    
    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case FOOD_OTHER:
            count = db.update("food_other", values, where, whereArgs);
            break;

        case FOOD_OTHER_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update("food_other", values, FoodOtherDataColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(FoodOtherDataDefinition.AUTHORITY, "food.other", FOOD_OTHER);
        sUriMatcher.addURI(FoodOtherDataDefinition.AUTHORITY, "food.other/#", FOOD_OTHER_ID);

        sFoodOtherDataProjectionMap = new HashMap<String, String>();
        sFoodOtherDataProjectionMap.put(FoodOtherDataColumns._ID, FoodOtherDataColumns._ID);
        sFoodOtherDataProjectionMap.put(FoodOtherDataColumns.DATE, FoodOtherDataColumns.DATE);
        sFoodOtherDataProjectionMap.put(FoodOtherDataColumns.CAFFEINE,FoodOtherDataColumns.CAFFEINE);
        sFoodOtherDataProjectionMap.put(FoodOtherDataColumns.SNACK,FoodOtherDataColumns.SNACK);
        sFoodOtherDataProjectionMap.put(FoodOtherDataColumns.HEALTHY,FoodOtherDataColumns.HEALTHY);

    }
}
